  package com.linewell.system.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linewell.commom.controller.BackendBaseController;
import com.linewell.system.model.SysRoles;
import com.linewell.system.pagemodel.DataGrid;
import com.linewell.system.pagemodel.PageHelper;
import com.linewell.system.pagemodel.ReturnInfo;
import com.linewell.system.service.ISysRolesService;

/**
 * 系统角色控制器
 */

@Controller
@RequestMapping("manage/sysRoles")
public class SysRolesController extends BackendBaseController {
	
	private static final Log log = LogFactory.getLog(SysRolesController.class);
	@Autowired
	private ISysRolesService sysRolesService;

	/**
	 * 跳转至 sys_roles_list页
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request) {
		return super.index("/WEB-INF/pages/system/sys_roles/sys_roles_list.jsp", request);
	}

	/**
	 * 数据查询
	 */
	@ResponseBody
	@RequestMapping(value = "/dataGrid")
	public DataGrid dataGrid(@ModelAttribute SysRoles c, PageHelper ph, HttpServletRequest request) {
		ph.setSort("createTime");
		ph.setOrder("desc");
		DataGrid dg = sysRolesService.datagrid(ph, c,getUserDepId(request));
		return dg;

	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add")
	public String add(Map<String, Object> map) {
		map.put("saveUrl", "/manage/sysRoles/addSave");
		return "/WEB-INF/pages/system/sys_roles/sys_roles_au.jsp";
	}

	/**
	 * 添加保存
	 */
	@ResponseBody
	@RequestMapping(value = "/addSave")
	public ReturnInfo addSave(@Valid SysRoles sysRoles, BindingResult b, ReturnInfo result,
			HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (sysRoles != null) {
				
					try {
						log.info(sysRoles.getSysDepartment().getDepId());
						if (sysRoles.getSysDepartment().getDepId() == 0) {
							sysRoles.setSysDepartment(null);
						}
						sysRoles.setCreateUserId((long) getLoginUserId(request));
						sysRolesService.save(sysRoles);
					} catch (Exception e) {
						log.info("保存失败" + e.getMessage());
						result.setMsg("保存失败！");
						
						result.setSuccess(1);
					}
				
			}
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/edit")
	public String edit(String id, Map<String, Object> map) {
		System.out.println("DHUOHA" + id);
		map.put("saveUrl", "/manage/sysRoles/editSave");
		if (id != null) {
			List<SysRoles> model = sysRolesService.getUser(id);
			map.put("model", model.get(0));
		}
		return "/WEB-INF/pages/system/sys_roles/sys_roles_au.jsp";
	}

	/**
	 * 修改保存
	 */
	@ResponseBody
	@RequestMapping(value = "/editSave")
	public ReturnInfo editSave(@Valid SysRoles sysRoles, BindingResult b, ReturnInfo result) {

		if (b.getErrorCount() > 0) { // 数据校验
			log.info("数据校验出错！");
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (sysRoles != null) {
				try {
					log.info(sysRoles.getSysDepartment().getDepId());
					if (sysRoles.getSysDepartment().getDepId() == 0) {
						sysRoles.setSysDepartment(null);
					}
					sysRolesService.update(sysRoles);
				} catch (Exception e) {
					log.info("保存失败" + e.getMessage());
					result.setMsg("保存失败！");
					result.setSuccess(1);
				}
				
				
				

			}
		}

		return result;
	}

	/**
	 * 删除（物理删除）
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public ReturnInfo delete(String ids, ReturnInfo result) {
		if (ids != null) {
			try {
				sysRolesService.deleteAll(ids);
			} catch (Exception e) {
				log.info("删除异常" + e.getMessage());
				result.setMsg("删除失败！");
				result.setSuccess(1);
			}
		}

		return result;
	}

	/**
	 * 移除（逻辑删除）
	 */
	@ResponseBody
	@RequestMapping(value = "/remove")
	public ReturnInfo remove(String ids, ReturnInfo result) {
		if (ids != null) {
			try {
				sysRolesService.removeAll(ids);
			} catch (Exception e) {
				log.info("移除异常" + e.getMessage());
				result.setMsg("移除失败！");
				result.setSuccess(1);
			}
		}
		return result;
	}
	/**
	 * 跳转sys_roles_set页面
	 * 
	 */
	@RequestMapping(value = "/roleSkip")
	public String roleSkip(Integer id, Map<String, Integer> map) {
		log.info(id);
		map.put("id", id);
		return "/WEB-INF/pages/system/sys_roles/sys_roles_set.jsp";
	}

	/**
	 * 获得角色菜单，用于数据回填
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/getRoleMenu")
	public ReturnInfo getRoleMenu(Integer gid, ReturnInfo info) {
		log.info(gid);
		if (gid != null) {
			String menus = "";
			try {
				SysRoles sysRole = sysRolesService.getRoleMenu(gid);
				if (sysRole != null)
					menus = sysRole.getRoleMenus();
				// log.info(menus);
			} catch (Exception e) {
				log.info("异常" + e.getMessage());
				e.printStackTrace();
			}
			info.setObj(menus);
		}
		return info;
	}

	/**
	 * 保存权限
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/saveAuthority")
	public ReturnInfo saveQuthority(String mids, Integer gid, ReturnInfo info) {

		if (mids != null && gid != null) {
			try {
				sysRolesService.saveAuthority(mids, gid);
			} catch (Exception e) {
				log.info("异常" + e.getMessage());
			}
		}
		return info;
	}
	
	/**
	 * 获取角色信息
	 */
	@ResponseBody
	@RequestMapping(value = "/getRoles")
     public DataGrid getRoles(HttpServletRequest request){
		
		DataGrid result=new DataGrid();
		List<SysRoles> sysRoles;
		try {
			sysRoles = sysRolesService.getRoles(getUserDepId(request));
		     result.setRows(sysRoles);
		} catch (Exception e) {
			// TODO: handle exception
			result.setSuccess(2);
			log.info("异常" + e.getMessage());
		}	
    	 return result;	 
     }
}
